


import { Typography, Input, Button, Space, Popover, Upload, Image } from 'antd'; // 引入 Upload 和 Image
import { PhoneOutlined, MailOutlined, EnvironmentOutlined, SmileOutlined, PictureOutlined, LinkOutlined, TagOutlined, CodeOutlined, CloseCircleOutlined, ShareAltOutlined, MessageOutlined } from '@ant-design/icons'; // 引入所需图标
import { useState, useRef } from 'react'; // 引入 useState 和 useRef

const { Title, Text } = Typography; // 引入 Text
const { TextArea } = Input; // 引入 TextArea

const Contact = () => {
  const [message, setMessage] = useState(''); // 添加状态管理留言内容
  const [popoverVisible, setPopoverVisible] = useState(false); // 控制表情面板可见性
  const [selectedImages, setSelectedImages] = useState<File[]>([]); // 状态：存储选中的多个图片文件
  const [previewImages, setPreviewImages] = useState<string[]>([]); // 状态：存储多个图片预览 URL
  const fileInputRef = useRef<HTMLInputElement>(null); // 引用隐藏的文件输入
  const maxChars = 1000; // 最大字符数
  
  // 留言列表状态
  const [messages, setMessages] = useState<{
    id: number;
    avatar: string;
    nickname: string;
    time: string;
    content: string;
    images: string[];
    likes: number;
    comments: number;
    isLiked: boolean;
    commentList?: {
      id: number;
      avatar: string;
      nickname: string;
      time: string;
      content: string;
    }[];
    showCommentInput?: boolean;
  }[]>([]);

  // 排序方式状态
  const [sortType, setSortType] = useState<'hot' | 'new'>('new');

  // 评论输入状态
  const [commentText, setCommentText] = useState('');
  const maxCommentChars = 200;

  // 定义表情列表
  const emojis = [
    '😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😉', '😊',
    '😋', '😎', '😍', '😘', '🥰', '😗', '😙', '😚', '🙂', '🤗',
    '🤩', '🤔', '🤨', '😐', '😑', '😶', '🙄', '😏', '😣', '😥',
    '😮', '🤐', '😯', '😪', '😫', '🥱', '😴', '😌', '😛', '😜',
    '😝', '🤤', '😒', '😓', '😔', '😕', '🙃', '🤑', '😲', '🙁',
    '😖', '😞', '😟', '😤', '😢', '😭', '😦', '😧', '😨', '😩',
    '🤯', '😬', '😰', '😱', '🥵', '🥶', '😳', '🤪', '😵', '🥴',
    '😠', '😡', '🤬', '😷', '🤒', '🤕', '🤢', '🤮', '🤧', '😇',
    '🥳', '🥺', '🤠', '🤡', '🤥', '🤫', '🤭', '🧐', '🤓', '😈',
    '👿', '👹', '👺', '💀', '👻', '👽', '🤖', '💩', '😺', '😸',
    '😹', '😻', '😼', '😽', '🙀', '😿', '😾'
  ];

  const contactInfo = [
    {
      icon: <PhoneOutlined className="text-3xl text-primary mb-3" />,
      text: '18627474375',
    },
    {
      icon: <MailOutlined className="text-3xl text-primary mb-3" />,
      text: 'gisjinger@163.com',
    },
    {
      icon: <EnvironmentOutlined className="text-3xl text-primary mb-3" />,
      text: '中国 南京 南京师范大学',
    },
  ];

  // 移除或注释掉未使用的 handleSubmit
  // const handleSubmit = (e: React.FormEvent) => {
  //   e.preventDefault();
  //   // 这里可以添加表单提交逻辑
  // };

  const handlePublish = () => {
    if (!message.trim() && previewImages.length === 0) return;
    
    const newMessage = {
      id: Date.now(),
      avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=' + Math.random(),
      nickname: '访客' + Math.floor(Math.random() * 1000),
      time: new Date().toLocaleString(),
      content: message,
      images: [...previewImages],
      likes: 0,
      comments: 0,
      isLiked: false,
      commentList: [],
      showCommentInput: false
    };
    
    setMessages(prev => [newMessage, ...prev]);
    setMessage(''); // 清空输入框
    setSelectedImages([]); // 清空选中的图片
    setPreviewImages([]); // 清空预览图片
  };

  // 处理表情选择
  const handleEmojiSelect = (emoji: string) => {
    setMessage(message + emoji);
    setPopoverVisible(false); // 选择后关闭 Popover
  };

  // 表情面板内容
  const emojiContent = (
    <div style={{ width: '300px', maxHeight: '200px', overflowY: 'auto' }}>
      <Space wrap>
        {emojis.map((emoji, index) => (
          <Button key={index} type="text" onClick={() => handleEmojiSelect(emoji)} style={{ fontSize: '18px', padding: '5px' }}>
            {emoji}
          </Button>
        ))}
      </Space>
    </div>
  );

  // 处理图片按钮点击
  const handlePictureClick = () => {
    fileInputRef.current?.click(); // 触发隐藏的文件输入框
  };

  // 处理文件选择
  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (files) {
      const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
      const newFiles: File[] = [];
      const newPreviewUrls: string[] = [];

      Array.from(files).forEach(file => {
        if (allowedTypes.includes(file.type)) {
          newFiles.push(file);
          const reader = new FileReader();
          reader.onloadend = () => {
            newPreviewUrls.push(reader.result as string);
            if (newPreviewUrls.length === newFiles.length) {
              setSelectedImages(prev => [...prev, ...newFiles]);
              setPreviewImages(prev => [...prev, ...newPreviewUrls]);
            }
          };
          reader.readAsDataURL(file);
        } else {
          console.error('不支持的文件类型');
        }
      });
    }
    // 清空 input value 允许重复选择相同文件
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // 移除选中的图片
  const handleRemoveImage = (index: number) => {
    setSelectedImages(prev => prev.filter((_, i) => i !== index));
    setPreviewImages(prev => prev.filter((_, i) => i !== index));
  };

  return (
    <section id="contact" className="py-section bg-background-gray z-10 relative">
      <div className="inner-width">
        <Title level={1} className="section-title">留言</Title>
        
        <div className="flex flex-wrap justify-between mb-16">
          {contactInfo.map((info, index) => (
            <div key={index} className="w-full md:w-[calc(33.33%-30px)] text-center mb-8 md:mb-0">
              {info.icon}
              <div>{info.text}</div>
            </div>
          ))}
        </div>

        {/* 新增留言板区域 */}
        <div className="message-board bg-white p-6 rounded-lg shadow-md">
          <div className="flex flex-col gap-4 mb-4">
            <TextArea
              rows={4}
              placeholder="给jinger留言吧～"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              maxLength={maxChars}
              className="w-full"
            />
            {/* 图片预览区域 */}
            {previewImages.length > 0 && (
              <div className="flex gap-2 flex-wrap">
                {previewImages.map((previewUrl, index) => (
                  <div key={index} className="relative w-24 h-24"> {/* 固定大小 */}
                    <Image
                      width={96}
                      height={96}
                      src={previewUrl}
                      alt={`预览 ${index + 1}`}
                      className="object-cover rounded"
                    />
                    <Button
                      type="text"
                      icon={<CloseCircleOutlined />}
                      onClick={() => handleRemoveImage(index)}
                      className="absolute top-0 right-0 bg-black bg-opacity-50 text-white rounded-full p-1 leading-none"
                      style={{ transform: 'translate(50%, -50%)' }}
                      size="small"
                    />
                  </div>
                ))}
              </div>
            )}
          </div>
          {/* 隐藏的文件输入框 */}
          <input
            type="file"
            ref={fileInputRef}
            onChange={handleFileChange}
            accept="image/jpeg,image/png,image/gif,image/webp" // 限制文件类型
            style={{ display: 'none' }}
            multiple // 允许多选
          />
          <div className="flex justify-between items-center">
            <Space>
              <Popover
                content={emojiContent}
                title="选择表情"
                trigger="click"
                open={popoverVisible}
                onOpenChange={setPopoverVisible}
              >
                <Button type="text" icon={<SmileOutlined />} />
              </Popover>
              <Button type="text" icon={<PictureOutlined />} onClick={handlePictureClick} /> {/* 添加 onClick 事件 */}
              {/* <Button type="text" icon={<LinkOutlined />} />
              <Button type="text" icon={<TagOutlined />} />
              <Button type="text" icon={<CodeOutlined />} /> */}
            </Space>
            <div className="flex items-center">
              <Text type="secondary" className="mr-4">
                {message.length}/{maxChars}
              </Text>
              <Button type="primary" onClick={handlePublish} disabled={!message.trim() && previewImages.length === 0}>
                发布
              </Button>
            </div>
          </div>         
          {/* 留言展示区域 */}
          <div className="mt-8">
            <div className="flex items-center justify-between mb-6 border-b pb-3">
              <div className="text-gray-600 text-lg font-medium">评论 {messages.length}</div>
              <div className="flex gap-6">
                <button
                  className={`text-sm hover:text-primary transition-colors ${sortType === 'hot' ? 'text-primary font-medium border-b-2 border-primary' : 'text-gray-500'}`}
                  onClick={() => setSortType('hot')}
                >
                  最热
                </button>
                <button
                  className={`text-sm hover:text-primary transition-colors ${sortType === 'new' ? 'text-primary font-medium border-b-2 border-primary' : 'text-gray-500'}`}
                  onClick={() => setSortType('new')}
                >
                  最新
                </button>
              </div>
            </div>
            <div className="space-y-6">
              {[...messages]
                .sort((a, b) => {
                  if (sortType === 'hot') {
                    return b.likes - a.likes;
                  }
                  return b.id - a.id;
                })
                .map((msg) => (
              <div key={msg.id} className="bg-white p-6 rounded-lg shadow-sm border border-gray-100 hover:shadow-md transition-shadow">
                <div className="flex items-center gap-3 mb-3">
                  <img src={msg.avatar} alt="avatar" className="w-10 h-10 rounded-full border-2 border-gray-100" />
                  <div className="flex-1">
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-base">{msg.nickname}</span>
                      <span className="text-gray-400 text-xs">{msg.time}</span>
                    </div>
                  </div>
                </div>
                <div className="text-base text-gray-700 mb-4 leading-relaxed">{msg.content}</div>
                {msg.images.length > 0 && (
                  <div className="flex gap-3 flex-wrap mb-4">
                    {msg.images.map((img, index) => (
                      <Image
                        key={index}
                        width={160}
                        height={160}
                        src={img}
                        alt={`图片 ${index + 1}`}
                        className="object-cover rounded-lg"
                      />
                    ))}
                  </div>
                )}
                <div className="flex items-center gap-6 text-gray-500">
                  <Button 
                    type="text" 
                    icon={<SmileOutlined className={msg.isLiked ? 'text-primary' : ''} />} 
                    onClick={() => {
                      setMessages(prev =>
                        prev.map(m =>
                          m.id === msg.id
                            ? { ...m, likes: m.isLiked ? m.likes - 1 : m.likes + 1, isLiked: !m.isLiked }
                            : m
                        )
                      );
                    }}
                    className={`hover:text-primary transition-colors ${msg.isLiked ? 'text-primary' : ''}`}
                  >
                    {msg.likes}
                  </Button>
                 {/*  <Button 
                    type="text" 
                    icon={<MessageOutlined />} 
                    onClick={() => {
                      setMessages(prev =>
                        prev.map(m =>
                          m.id === msg.id
                            ? { ...m, showCommentInput: !m.showCommentInput }
                            : m
                        )
                      );
                    }}
                    className="hover:text-primary transition-colors"
                  >
                    {msg.comments}
                  </Button> */}
                  {/* 评论输入区域 */}
                  {msg.showCommentInput && (
                    <div className="mt-4 bg-gray-50 rounded-lg p-4 border border-gray-100">
                      <div className="block w-full">
                        <TextArea
                          placeholder="平等表达，友善交流"
                          value={commentText}
                          onChange={(e) => setCommentText(e.target.value)}
                          maxLength={maxCommentChars}
                          autoSize={{ minRows: 2, maxRows: 4 }}
                          className="w-full mb-3 text-sm border-gray-200 rounded focus:border-primary focus:shadow-none"
                        />
                        <div className="flex items-center justify-between">
                          <div className="text-gray-400 text-sm">
                            {commentText.length}/{maxCommentChars}
                          </div>
                          <Button 
                            type="primary"
                            onClick={() => {
                              if (!commentText.trim()) return;
                              
                              const newComment = {
                                id: Date.now(),
                                avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=' + Math.random(),
                                nickname: '访客' + Math.floor(Math.random() * 1000),
                                time: new Date().toLocaleString(),
                                content: commentText
                              };
                              
                              setMessages(prev =>
                                prev.map(m =>
                                  m.id === msg.id
                                    ? {
                                        ...m,
                                        comments: m.comments + 1,
                                        commentList: [...(m.commentList || []), newComment]
                                      }
                                    : m
                                )
                              );
                              setCommentText('');
                            }}
                            className="px-6"
                          >
                            发布
                          </Button>
                        </div>
                      </div>
                    </div>
                  )}
                  {/* 评论列表 */}
                  {msg.commentList && msg.commentList.length > 0 && (
                    <div className="mt-4 space-y-4 pl-6 border-l-2 border-gray-100">
                      {msg.commentList.map((comment) => (
                        <div key={comment.id} className="flex items-start gap-3 bg-gray-50 p-3 rounded-lg">
                          <img src={comment.avatar} alt="avatar" className="w-8 h-8 rounded-full border border-gray-200" />
                          <div className="flex-1">
                            <div className="flex items-center gap-2 mb-1">
                              <span className="font-medium text-sm">{comment.nickname}</span>
                              <span className="text-gray-400 text-xs">{comment.time}</span>
                            </div>
                            <div className="text-sm text-gray-700">{comment.content}</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
    </section>
  );
};

export default Contact;